package com.qrxl.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qrxl.user.entity.UserRole;
import com.qrxl.user.mapper.UserRoleMapper;
import com.qrxl.user.service.IUserRoleService;
import com.qrxl.user.vo.req.UserRelRoleReq;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色关联 服务实现类
 * </p>
 *
 * @author friday
 * @since 2020-12-05
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Override
    @Transactional
    public void relRoles(UserRelRoleReq req) {
        UserRole cond = new UserRole();
        cond.setUserId(req.getUserId());
        List<UserRole> dbList = baseMapper.selectList(Wrappers.query(cond));
        List<UserRole> insertList = req.getRoleIdList().stream()
                .filter(one -> !dbList.stream().anyMatch(two -> two.getRoleId().equals(one)))
                .map(one -> {
                    UserRole insert = new UserRole();
                    insert.setUserId(req.getUserId());
                    insert.setRoleId(one);
                    return insert;
                }).collect(Collectors.toList());

        List<String> deleteList = dbList.stream()
                .filter(one -> !req.getRoleIdList().stream().anyMatch(two -> two.equals(one.getRoleId())))
                .map(UserRole::getId).collect(Collectors.toList());

        deleteList.forEach(id -> {
            baseMapper.deleteById(id);
        });
        insertList.forEach(one -> {
            baseMapper.insert(one);
        });
    }
}
